import { ref, computed } from 'vue'

export function useTimer() {
  const startTime = ref<number | null>(null) // 开始时间戳
  const elapsedTime = ref<number>(0)         // 已过时间（毫秒）
  const isRunning = ref<boolean>(false)      // 是否正在运行
  const timerId = ref<number | null>(null)   // 定时器 ID

  // 更新计时器
  const updateTimer = () => {
    if (isRunning.value) {
      const now = Date.now()
      if (startTime.value !== null) {
        elapsedTime.value = now - startTime.value
      }
      timerId.value = setTimeout(() => {
        updateTimer()
      }, 1000)
    }
  }

  // 启动计时器
  const start = () => {
    if (isRunning.value) return
    startTime.value = Date.now() - elapsedTime.value
    isRunning.value = true
    updateTimer()
  }

  // 暂停计时器
  const pause = () => {
    isRunning.value = false
    if (timerId.value !== null) {
      clearTimeout(timerId.value)
      timerId.value = null
    }
  }

  // 重置计时器
  const reset = () => {
    pause()
    elapsedTime.value = 0
    startTime.value = null
  }

  // 格式化输出 mm:ss 或 hh:mm:ss
  const formattedTime = computed(() => {
    const totalSeconds = Math.floor(elapsedTime.value / 1000)
    const hours = String(Math.floor(totalSeconds / 3600)).padStart(2, '0')
    const minutes = String(Math.floor((totalSeconds % 3600) / 60)).padStart(2, '0')
    const seconds = String(totalSeconds % 60).padStart(2, '0')

    if (hours === '00') {
      return `${minutes}:${seconds}`
    }
    return `${hours}:${minutes}:${seconds}`
  })

  return {
    isRunning,
    formattedTime,
    start,
    pause,
    reset,
    elapsedTime, // 可选：获取原始毫秒数
  }
}